package com.yunfeisoft.controller.interceptor;

import com.applet.session.DomainModel;
import com.applet.session.SessionModel;
import com.applet.session.UserSession;
import com.applet.utils.AjaxUtils;
import com.applet.utils.Constants;
import com.applet.utils.KeyUtils;
import com.yunfeisoft.model.User;
import com.yunfeisoft.service.inter.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.List;

/**
 * 登录验证拦截器
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = Logger.getLogger(AuthInterceptor.class);

    @Autowired
    private UserSession userSession;
    @Autowired
    private DomainModel domainModel;
    @Autowired
    private UserService userService;

    private AntPathMatcher pathMatcher = new AntPathMatcher();
    private String viewPath = "/view/**";
    private String controllerPath = "/web/**";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (Constants.is_log) {
            return false;
        }
        String uri = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (!pathMatcher.match(viewPath, uri) && !pathMatcher.match(controllerPath, uri)) {
            return super.preHandle(request, response, handler);
        }

        /*log.info("################################### 1##");
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.info(key + " : " + value);
        }
        log.info("################################### 2##");*/

        /*String openId = request.getHeader("authority-id");
        log.info("openId = " + openId);*/

        SessionModel sessionModel = userSession.getSessionModel();
        sessionModel = (sessionModel == null) ? loginIn(request, response) : sessionModel;

        if (sessionModel != null) {
            request.setAttribute(Constants.SESSION_MODEL, sessionModel);
            userSession.resetSessionTime();
            return true;
        }

        if (uri.startsWith("/view")) {
            response.sendRedirect(domainModel.getWebDomain() + "/time-out.htm");
        } else {
            AjaxUtils.ajaxJsonErrorMessage("会话失效，请重新登录");
        }
        return false;
    }

    /**
     * 重新登录（小程序端使用）
     *
     * @param request
     * @param response
     * @return
     */
    private SessionModel loginIn(HttpServletRequest request, HttpServletResponse response) {
        String openId = request.getHeader("authority-id");
        //log.info("openId2 = " + openId);
        if (StringUtils.isBlank(openId)) {
            return null;
        }

        List<User> userList = userService.queryByOpenId(openId);

        if (userList.isEmpty()) {
            return null;
        }
        /*if (userList.size() > 1) {
            return null;
        }*/

        User user = userList.get(0);
        SessionModel sessionModel = new SessionModel();
        sessionModel.setUser(user);
        sessionModel.setToken(openId);
        user.setToken(sessionModel.getToken());

        userSession.storageSessionModel(sessionModel);
        //request.setAttribute(Constants.SESSION_MODEL, sessionModel);
        return sessionModel;
    }
}
